import React, { Component } from 'react'
import { Toast } from 'antd-mobile'
import axios from 'axios'
import { getCurrentCity, setCity } from '@/utils/city'

import { AutoSizer, List } from 'react-virtualized'
import 'react-virtualized/styles.css'
import style from './index.module.scss'
import NavHeader from '@/common/NavHeader'
//假数据
// const list = Array.from(new Array(1000)).map(
//   (item, index) => `这是第${index}条数据`
// )
// console.log(list)

const TITLE_HEIGHT = 36
const CITY_HEIGHT = 50
const HOT_CITY = ['北京', '上海', '广州', '深圳']

export default class City extends Component {
  constructor(props) {
    super(props)
    this.listRef = React.createRef()
  }
  state = {
    cityObj: {},
    cityArr: [],
    currentIndex: 0,
  }
  async componentDidMount() {
    Toast.loading('拼命加载中...', 0)
    await this.getCityList()
    Toast.hide()
  }
  async getCityList() {
    const res = await axios.get('http://localhost:8080/area/city?level=1')

    const { status, body } = res.data
    if (status === 200) {
      const { cityObj, cityArr } = this.parseCityList(body)
      //处理热门城市
      const resHot = await axios.get('http://localhost:8080/area/hot')
      const { status } = resHot.data
      if (status === 200) {
        cityArr.unshift('hot')
        cityObj['hot'] = resHot.data.body
        // console.log(cityObj, cityArr)
      }

      // 处理当前定位城市
      //回调函数实现
      // getCurrentCity((currentCity) => {
      //   console.log(currentCity, 31)
      // })

      //promise 实现
      const currentCity = await getCurrentCity()
      console.log(currentCity)
      cityArr.unshift('#')
      cityObj['#'] = [currentCity]

      this.setState({ cityObj, cityArr }, () => {
        //  在城市数据回来后, 计算高度
        this.listRef.current.measureAllRows()
      })

      console.log(cityObj, cityArr)
      // console.log(cityObj)
      // console.log(cityArr)
    }
  }

  // 用于处理城市数据
  parseCityList(body) {
    // 希望得到一个对象, 这个对象格式: { a: [], b: [], ... }
    const cityObj = {}
    body.forEach((item) => {
      const short = item.short.slice(0, 1)
      // console.log(short)
      if (short in cityObj) {
        cityObj[short].push(item)
      } else {
        cityObj[short] = [item]
      }
    })
    // console.log(cityObj)
    //除了`cityObj`, 还需要获取一个数组,
    //这个数组中存储了, 所有城市的简写(对象的键),
    //这个数组还要有顺序
    const cityArr = Object.keys(cityObj).sort()
    // console.log(cityArr)
    // 将解析得到的对象和数组返回
    return {
      cityObj,
      cityArr,
    }
  }

  //行渲染
  rowRenderer({ key, index, isScrolling, isVisible, style }) {
    const { cityArr, cityObj } = this.state
    //获取标题
    const title = cityArr[index]
    const citys = cityObj[title]
    return (
      <div key={key} style={style} className="city-item">
        <div className="title">{this.parseTitle(title)}</div>
        {citys.map((item) => (
          <div
            key={item.value}
            className="name"
            onClick={() => this.selectCity(item)}
          >
            {item.label}
          </div>
        ))}
      </div>
    )
  }
  // 处理标题的问题
  parseTitle(title) {
    if (title === '#') {
      return '当前城市'
    } else if (title === 'hot') {
      return '热门城市'
    } else {
      return title.toUpperCase()
    }
  }
  //动态计算每一行的高度
  calcHeight = ({ index }) => {
    const { cityArr, cityObj } = this.state
    //获取标题
    const title = cityArr[index]
    const citys = cityObj[title]
    return TITLE_HEIGHT + citys.length * CITY_HEIGHT
  }

  //滚动城市列表让对应的索引高亮
  onRowsRendered = ({ startIndex }) => {
    if (startIndex === this.state.currentIndex) return
    this.setState({
      currentIndex: startIndex,
    })
  }

  //点击索引置顶该索引城市
  handleCityIndexItem = (index) => {
    console.log(index)
    this.listRef.current.scrollToRow(index)
  }

  //选择城市
  selectCity = (city) => {
    if (HOT_CITY.includes(city.label)) {
      //存本地
      setCity(city)
      this.props.history.go(-1)
    } else {
      Toast.info('该城市没有更多房源信息', 2, null, false)
    }
  }
  render() {
    return (
      <div className={style.city}>
        {/* 头部导航 */}
        <NavHeader>城市选择</NavHeader>
        {/* 城市列表 */}
        <AutoSizer>
          {({ height, width }) => (
            <List
              ref={this.listRef}
              scrollToAlignment="start"
              width={width}
              height={height}
              rowCount={this.state.cityArr.length}
              rowHeight={this.calcHeight.bind(this)}
              rowRenderer={this.rowRenderer.bind(this)}
              onRowsRendered={this.onRowsRendered.bind(this)}
            />
          )}
        </AutoSizer>
        {/* 右侧城市索引列表： */}
        <ul className="city-index">
          {this.state.cityArr.map((item, index) => (
            <li
              key={item}
              className="city-index-item"
              onClick={() => {
                this.handleCityIndexItem(index)
              }}
            >
              <span
                className={
                  index === this.state.currentIndex ? 'index-active' : ''
                }
              >
                {item === 'hot' ? '热' : item.toUpperCase()}
              </span>
            </li>
          ))}
        </ul>
      </div>
    )
  }
}
